﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;

namespace WindowsFormsApp1
{
    public class ScheduledTask
    {
        public string Name { get; set; }
        public int Interval { get; set; }
        public bool IsActive { get; set; }
        public DateTime NextRunTime { get; private set; }
        public DateTime LastRunTime { get; private set; }
        public int RunCount { get; private set; }

        private System.Timers.Timer timer;
        private Action taskAction;
        private SynchronizationContext uiContext;
        public ScheduledTask(string name, int interval, Action action, SynchronizationContext context = null)
        {
            Name = name;
            Interval = interval;
            taskAction = action;
            IsActive = true;
            RunCount = 0;
            uiContext = context;

            timer = new System.Timers.Timer(interval * 1000);
            timer.Elapsed += OnTimerElapsed;
            timer.AutoReset = true;

            CalculateNextRunTime();
            timer.Start();
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (!IsActive) return;

            LastRunTime = DateTime.Now;
            RunCount++;
            CalculateNextRunTime();

            if (uiContext != null)
            {
                // 有UI上下文时，确保在UI线程执行
                uiContext.Post(_ => taskAction(), null);
            }
            else
            {
                // 没有UI上下文时直接执行（可能不是UI操作）
                taskAction();
            }
        }

        private void CalculateNextRunTime()
        {
            NextRunTime = DateTime.Now.AddSeconds(Interval);
        }

        public void Pause()
        {
            IsActive = false;
            timer.Stop();
        }

        public void Resume()
        {
            IsActive = true;
            timer.Start();
            CalculateNextRunTime();
        }

        public void Stop()
        {
            timer.Stop();
            timer.Dispose();
        }

        public void UpdateInterval(int newInterval)
        {
            Interval = newInterval;
            timer.Interval = newInterval * 1000;
            CalculateNextRunTime();
        }
    }
}
